'use strict';
import Base from './base.js';
import path from 'path';
import superagent from 'superagent';
import cheerio from 'cheerio';
import eventproxy from 'eventproxy';
import zhihu from 'zhihu'

export default class extends Base {
	/**
	 * index action
	 * @return {Promise} []
	 */
	indexAction(){
		let username = 'mark940721';

		zhihu.User.info(username).then(function(user){
		  console.log(user);
		});

		let topicID = '19583739';
		zhihu.Topic.getTopicByID(topicID).then(function(result){
		  console.log(result);
		});

		let Question = require('zhihu').Question;

		Question.answers('20269059').then(function(result){
		  console.log(result);
		});
		return this.success();
	}
	listAction() {
		let ep = new eventproxy(),pageUrls = [],page = parseInt(this.get('page')|| 1);

		let key = page <= 1? 'index': `index_${page-1}`;

		pageUrls.push(`http://www.changsha.gov.cn/xxgk/szfxxgkml/ghjh/qsfzgh/${key}.html`);

		pageUrls.forEach(pageUrl => {
			console.log(pageUrl);
			superagent
				.get(pageUrl)
				.end((err, pres) => {
					let $ = cheerio.load(pres.text);
					let $newsList = $('.table_newest>tr');

					err === null? $newsList.each((i, elem) => {
					  	let url = $(elem).find('.docTitle2>a').eq(0).attr('href');
					  	let describe = $(elem).find('.docTitle2>a').eq(0).text();
					  	let time = $(elem).find('.ul_docInfo>li').eq(2).text();
					  	let title = $(elem).find('.li_docTitle').eq(0).text();

					  	title !== '' && (title = title.substring(7, title.length));

					  	url && ep.emit('ArticleHtml', {
							url: url,
							desc:describe,
							title: title,
							time:time,
						});
					}): this.fail(err.status,"抓取错误！");
				});
		});

		ep.after('ArticleHtml', pageUrls.length*10 ,articlesArray => {
			console.log(articlesArray.length);
	        // 当所有 'ArticleHtml' 事件完成后的回调触发下面事件
			this.success(articlesArray);
        });
	}
	articleAction(){
		let url = this.get('url'),
			baseUrl = 'http://www.changsha.gov.cn/xxgk/szfxxgkml/ghjh/qsfzgh/',
			pageUrl = `${baseUrl}${url}`,
			articleRootPath = path.dirname(pageUrl);

			console.log(pageUrl);
			console.log(articleRootPath);
		superagent
				.get(pageUrl)
				.end((err, pres) => {
					if(err === null){
						let $ = cheerio.load(pres.text);
						let content = $('#docContent_detail').html()
										.replace(/ style\=\"[^\<\>\=\"]*\"/g, '')
										.replace(/ id\=\".*\"/g, '')
										.replace(/ class\=\".*\"/g, '')
										.replace(/src=\"\./g, `src=\"${articleRootPath}`);
						this.success(content);
					}else{
						this.fail(err.status,"抓取错误！");
					}
				})
	}
}